package com.beyond.market.user.shiro;

import com.beyond.market.user.domain.User;
import com.beyond.market.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLException;

//自定义如何判断用户认证和授权的 spring-shiro.xml  <bean ShiroFilterFactoryBean>
public class UserRealm extends AuthorizingRealm {
    //导入ServiceImpl
    @Autowired
    private UserService userService;

    private User loginUser;
    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //1.创建简单授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        try {
           String perms = userService.getPermsByUserName(loginUser.getUserId());
           info.addStringPermission(perms);
        }catch(SQLException e){
        }
        return info;
    }
    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
                                                                   throws AuthenticationException {
        //1.从token中拿到用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String name = token.getUsername();
        try {
            //2.调用Service根据用户名到数据库中查询哪个用户
            loginUser =  userService.getByName(name);
            //3.如果查询没有结果，则抛出未知账号异常
            if(loginUser == null){
                throw new UnknownAccountException();
            }
        }catch (SQLException e) {
            return null;
        }
        //5.创建一个简单的主角集合
        SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
        principalCollection.add(loginUser,"userRealm");

        //4.如果没问题不抛异常，创建简单的认证信息(主角集合（登录的对象放入），登录用户实际的数据库里的密码(转成char数组))
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                            principalCollection,loginUser.getUserPassword().toCharArray());
        return info;
    }
}
